﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using App.Data;
using App.Core.Data;
using App.Core.Logging;
using App.Logging.Logging;
using App.Web.Capsule.Modules;
using App.Web.References;
using App.Core.Cache;
using App.Cache;
using App.Web.Filter;

namespace App.Web.Capsule
{
    public class WebCapsule
    {
        const string NameOrConnectionString = "name=AppDbConnection";
        public void Initialise(HttpConfiguration config)
        {
            var builder = new ContainerBuilder();
            builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerLifetimeScope();
            builder.RegisterFilterProvider();
            builder.Register<IDbContext>(x => {
                ILogger logger = x.ResolveOptional<ILogger>();
                var context = new AppDbContext(NameOrConnectionString, logger);
                return context;
            }).InstancePerLifetimeScope();
            builder.Register(x => NLogLogger.Instance).SingleInstance();

            builder.RegisterModule<RepositoryCapsuleModule>();
            builder.RegisterModule<ServiceCapsuleModule>();
            builder.RegisterModule<ControllerCapsuleModule>();
            builder.RegisterModule<CacheCapsuleModule>();

            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 
            var resolver = new AutofacWebApiDependencyResolver(container);
            config.DependencyResolver = resolver;
        }
    }
}